import 'package:flutter/material.dart';
import '../empty_widget.dart';
import 'refresh_configure.dart';
import 'refresh_header.dart';
import 'refresh_footer.dart';
import 'refresh_fail.dart';

/// 组合EasyRefresh特性，添加自定义特性
import 'package:flutter_easyrefresh/easy_refresh.dart';

/// 第一次失败后触发按钮刷新功能 - Trigger:触发器
// typedef TriggerCallback = void Function();

class RefreshWidget extends StatefulWidget {
  final RefreshConfigure refreshConfig;
  final List<Widget> slivers;
  final Color backgroundColor;
  RefreshWidget({Key key, @required this.slivers, this.refreshConfig, this.backgroundColor})
      : super(key: key);
  @override
  _RefreshWidgetState createState() => _RefreshWidgetState();
}

class _RefreshWidgetState extends State<RefreshWidget> {
  EasyRefreshController _controller;

  /// 刷新数据源没有数据
  bool _isNoData;

  /// 加载数据源没有数据
  bool _isNoMore;

  ///  刷新失败标记
  bool _isFail;

  RefreshHeader _getRefershHeader() {
    return widget.refreshConfig.refershHeader ?? RefreshConfigure.defaultHeader;
  }

  RefreshFooter _getRefershFooter() {
    return widget.refreshConfig.refreshFooter ?? RefreshConfigure.defaultFooter;
  }

  /// 暂不支持自定义
  RefreshFail _getRefreshFail(Color backgroundColor) {
    return RefreshFail(refreshCallback: () {
      _callRefresh();
    }, backgroundColor: backgroundColor,);
    // return EmptyWidget();
  }

  Widget _getRefreshEmpty(Color backgroundColor) {
    // return widget.refreshConfig.refreshEmpty ??
    //     null; //RefreshConfigure.defaultEmpty;
    return EmptyWidget(
        onTap: () {
          _callRefresh();
        },
        status: EmptyStatus.CONNECT, backgroundColor: backgroundColor,);
  }

  Widget _getRefreshFirst(Color backgroundColor) {
    // return widget.refreshConfig.refreshFirst ??
    //     null; //RefreshConfigure.defaultFirst;
    return EmptyWidget(status: EmptyStatus.LOADING, backgroundColor: backgroundColor,);
  }

  @override
  void initState() {
    _controller = EasyRefreshController();
    _isNoData = false;
    _isNoMore = false;
    _isFail = false;

    widget.refreshConfig.callRefresh = () {
      _callRefresh();
    };
    super.initState();
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (widget.refreshConfig.needContrType == 1) {
      return EasyRefresh.custom(
        slivers: widget.slivers,
        onLoad: _isNoMore
            ? null
            : (widget.refreshConfig.onLoad != null ? _onLoad : null),
        onRefresh: widget.refreshConfig.onRefresh != null ? _refresh : null,
        controller: _controller,
        enableControlFinishRefresh: true,
        enableControlFinishLoad: true,
        emptyWidget: _isNoData
            ? (_isFail ? _getRefreshFail(widget.backgroundColor) : _getRefreshEmpty(widget.backgroundColor))
            : null,
        firstRefresh: widget.refreshConfig.isFirstStart,
        firstRefreshWidget: _getRefreshFirst(widget.backgroundColor),
        header: _getRefershHeader().getRealHeader(),

        /// 通过外部传入的参数，输出 Footer 对象，供 EasyRefresh 使用
        footer: _getRefershFooter().getRealFooter(),
      );
    } else if (widget.refreshConfig.needContrType == 2) {
      return EasyRefresh(
        child: widget.slivers.first,
        controller: _controller,
        onRefresh: widget.refreshConfig.onRefresh != null ? _refresh : null,
        onLoad: _isNoMore
            ? null
            : (widget.refreshConfig.onLoad != null ? _onLoad : null),
        enableControlFinishLoad: true,
        enableControlFinishRefresh: true,
        emptyWidget: _isNoData
            ? (_isFail ? _getRefreshFail(widget.backgroundColor) : _getRefreshEmpty(widget.backgroundColor))
            : null,
        firstRefresh: widget.refreshConfig.isFirstStart,
        firstRefreshWidget: _getRefreshFirst(widget.backgroundColor),
        header: _getRefershHeader().getRealHeader(),
        footer: _getRefershFooter().getRealFooter(),
      );
    } else {
      return SizedBox();
    }
  }

  /// 上拉加载更多
  Future _onLoad() async {
    if (widget.refreshConfig.onLoad != null) {
      /// 恢复刷新状态(用于没有更多后)
      _controller.resetRefreshState();
      widget.refreshConfig.onLoad((loadMoreStatus, {isNoData: false}) {
        /// 外部加载完成，信息通知内部进行相关操作
        // _isNoMore = isNoData;
        /**
         *  _success = success;
         *  _noMore = _success == false ? false : noMore;
        */
        switch (loadMoreStatus) {
          case LoadMoreStatus.nomore:
            // _isNoMore = true;
            _controller.finishLoad(success: true, noMore: true);
            // _controller.finishLoad(success:true ,noMore: false);
            break;
          case LoadMoreStatus.idle:
            _controller.finishLoad(success: true, noMore: false);
            break;
          case LoadMoreStatus.fail:
            _controller.finishLoad(success: false);
            break;
          default:
        }
      });
    }
  }

  /// 下拉刷新
  Future _refresh() async {
    if (widget.refreshConfig.onRefresh != null) {
      /// 恢复加载状态(用于没有更多后)
      _isNoMore = false;
      _controller.resetLoadState();
      widget.refreshConfig.onRefresh((loadMoreStatus, {isNoData: false}) {
        /// 外部加载完成，信息通知内部进行相关操作
        _isNoData = isNoData;
        _isFail = loadMoreStatus == LoadMoreStatus.fail;
        if (_isNoData) {
          _isNoMore = true;
        }
        switch (loadMoreStatus) {
          case LoadMoreStatus.nomore:
            _controller.finishRefresh(noMore: true);
            _controller.resetRefreshState();
            break;
          case LoadMoreStatus.idle:
            _controller.finishRefresh(success: true);
            break;
          case LoadMoreStatus.fail:

            /// 请求失败 并且 数据源为空，需显示触发刷新界面
            _controller.finishRefresh(success: false);
            break;
          default:
        }
      });
    }
  }

  void _callRefresh() {
    _controller.callRefresh();
  }
}
